﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using Manager;
namespace HealthSystem.Map
{
    /// <summary>
    /// Summary description for MapHander
    /// </summary>
    public class MapHander : IHttpHandler
    {
        JavaScriptSerializer jser = new JavaScriptSerializer();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            Hander(context);
        }
        public void Hander(HttpContext context)
        {
            TMap map = new TMap();
            Tip tip = new Tip();
            string saction = context.Request["saction"];
            switch (saction)
            {
                case "new":
                    try
                    {
                        
                        if (context.Request["U"] != null)
                        {
                            map = jser.Deserialize<TMap>(context.Request["U"]);
                            var profile = HttpContext.Current.Profile as ProfileComm;
                            map.skey = context.Request["skey"];
                            map.stype = context.Request["stype"];
                            if (Add(map) == 1)
                            {
                                tip.result = true;
                                tip.message = "新增地图成功";
                            }
                            else
                            {
                                tip.result = false;
                                tip.message = "新增地图失败";
                            }
                           context.Response.Write(jser.Serialize(tip));
                        }
                    }
                    catch
                    {
                        tip.result = false;
                        tip.message = "新增地图错误";
                        context.Response.Write(jser.Serialize(tip));
                    }
                    finally
                    {

                    }
                    break;
                case "show":
                    try
                    {
                        string skey = context.Request["skey"];
                        string stype = context.Request["stype"];
                        if (!string.IsNullOrEmpty(skey))
                        {
                            var dt = GetMap(skey, stype);
                            if (dt.Rows.Count > 0)
                            {
                                map.skey = skey;
                                map.x = dt.Rows[0]["x"] is DBNull ? 0 : Convert.ToDouble(dt.Rows[0]["x"]);
                                map.y = dt.Rows[0]["y"] is DBNull ? 0 : Convert.ToDouble(dt.Rows[0]["y"]);
                                map.stype = dt.Rows[0]["stype"] is DBNull ? "" : dt.Rows[0]["stype"].ToString();
                                map.Name = dt.Rows[0]["name"] is DBNull ? "" : dt.Rows[0]["name"].ToString();
                                context.Response.Write(jser.Serialize(map));
                            }
                            else
                            {
                                context.Response.Write(jser.Serialize(new TMap()));
                            }
                        }
                    }
                    catch
                    {
                    }
                    break;
                case "GetDetail":
                    try
                    {
                        string skey = context.Request["skey"];
                        string stype = context.Request["stype"];
                        if (!string.IsNullOrEmpty(skey))
                        {
                            if (stype == "School")
                            {
                                HW_SchoolManager schoolManager = new HW_SchoolManager();
                                var school = schoolManager.GetById(skey);
                                context.Response.Write(jser.Serialize(school));

                            }
                            else if (stype == "Org")
                            {
                                HW_OrgDetailManager orgManager = new HW_OrgDetailManager();
                                var org = orgManager.GetById(skey);
                                context.Response.Write(jser.Serialize(org));
                            }
                        }
                    }
                    catch
                    {
                    }
                    break;
                case "districtMap":
                    try
                    {

                        string skey = context.Request["skey"];
                        string stype = context.Request["stype"];
                        if (stype == "School")
                        {
                            HW_SchoolManager manager = new HW_SchoolManager();
                            var school= manager.GetById(skey);
                            if (school != null)
                            {
                                var cityid= school.CityId;
                                var dt = GetMap(cityid, "City");

                                if (dt.Rows.Count > 0)
                                {
                                    map.skey = skey;
                                    map.x = dt.Rows[0]["x"] is DBNull ? 0 : Convert.ToDouble(dt.Rows[0]["x"]);
                                    map.y = dt.Rows[0]["y"] is DBNull ? 0 : Convert.ToDouble(dt.Rows[0]["y"]);
                                    map.stype = dt.Rows[0]["stype"] is DBNull ? "" : dt.Rows[0]["stype"].ToString();
                                    context.Response.Write(jser.Serialize(map));
                                }
                                else
                                {
                                    context.Response.Write(jser.Serialize(new TMap()));
                                }
                            }
                        }
                        else if (stype == "Org")
                        {
                            HW_OrgManager orgmanager = new HW_OrgManager();
                            var org = orgmanager.GetById(skey);
                            if (org != null)
                            {
                                var cityid = org.CityId;
                                var dt = GetMap(cityid, "City");
                                if (dt.Rows.Count > 0)
                                {
                                    map.skey = skey;
                                    map.x = dt.Rows[0]["x"] is DBNull ? 0 : Convert.ToDouble(dt.Rows[0]["x"]);
                                    map.y = dt.Rows[0]["y"] is DBNull ? 0 : Convert.ToDouble(dt.Rows[0]["y"]);
                                    map.stype = dt.Rows[0]["stype"] is DBNull ? "" : dt.Rows[0]["stype"].ToString();
                                    context.Response.Write(jser.Serialize(map));
                                }
                                else
                                {
                                    context.Response.Write(jser.Serialize(new TMap()));
                                }
                            }
                        }
                    }
                    catch
                    {
                    }
                    break;
            }
        }
        private string connstring = System.Configuration.ConfigurationManager.ConnectionStrings["HealthServices"].ToString();
        public DataTable GetMap(string skey,string stype)
        {
            string sql = string.Empty;
            if (stype == "Org")
            {
                sql = "select a.*,b.OrgName name from Tmap a left join HW_Org  b on a.skey=b.orgcode where skey=@skey";
            }
            else if (stype == "School")
            {
                sql = "select a.*,b.name name from Tmap a left join HW_School b on a.skey=b.Schoollcode where skey=@skey";
            }
            else
            {
                sql = "select * from Tmap where skey=@skey";
            }
            SqlConnection conn = new SqlConnection(connstring);
            try
            {
                SqlParameter[] sp = new SqlParameter[]{
                new SqlParameter("@skey",skey),
            };
                SqlCommand comm = new SqlCommand(sql, conn);
                comm.Parameters.AddRange(sp);
                DataSet ds = new DataSet();
                if (conn.State == ConnectionState.Closed)
                    conn.Open();
                SqlDataAdapter sda = new SqlDataAdapter(comm);
                sda.Fill(ds);
                return ds.Tables[0];
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
        public int Add(TMap map)
        {
            DataTable dt = GetMap(map.skey,map.stype);
            if (dt.Rows.Count > 0)
            {
                int n=Update(map);
                return n;
            }
            else
            {
                string sql = "insert into Tmap values(@skey,@x,@y,@stype)";
                SqlConnection conn = new SqlConnection(connstring);
                try
                {
                    SqlParameter[] sp = new SqlParameter[]{
                new SqlParameter("@skey",map.skey),
                new SqlParameter("@x",map.x),
                new SqlParameter("@y",map.y),
                new SqlParameter("@stype",map.stype)
            };
                    SqlCommand comm = new SqlCommand(sql, conn);
                    comm.Parameters.AddRange(sp);
                    if (conn.State == ConnectionState.Closed)
                        conn.Open();
                    int n = comm.ExecuteNonQuery();
                    return n;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    conn.Close();
                }
            }
        }
        public int Update(TMap map)
        {
            string sql = "update Tmap set x=@x,y=@y where skey=@skey";
            SqlParameter[] sp = new SqlParameter[]{
                new SqlParameter("@x",map.x),
                new SqlParameter("@y",map.y),
                new SqlParameter("@skey",map.skey)
            };
            SqlConnection conn = new SqlConnection(connstring);
            try
            {
                SqlCommand comm = new SqlCommand(sql, conn);
                comm.Parameters.AddRange(sp);
                if (conn.State == ConnectionState.Closed)
                    conn.Open();
                int n = comm.ExecuteNonQuery();
                return n;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
  
    public class TMap{
        public string skey{get;set;}
        public double x{get;set;}
        public double y { get; set; }
        public string stype{get;set;}
        public string Name { get; set; }
    }
    public class Tip
    {
        public bool result { get; set; }
        public string message { get; set; }
    }

}